/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package escom.ipn.modelo.dao;
import escom.ipn.modelo.dto.loginClass;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author Daniel
 */
public class loginDAO_1 {
  
    public static final String SQL_SELECT =
            "select * from USUARIO where usuario= ? and password = ? ";
    public static final String SQL_INSERT =
            "insert into USUARIO(usuario,password) values(?, ?) ";


    public loginClass loadLogin(loginClass a,Connection conn)
            throws SQLException {
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(SQL_SELECT);
            ps.setString(1, a.getUsuario());
            ps.setString(2, a.getPassword());
            rs = ps.executeQuery();
            List resultados = getResults(rs);
            if (resultados.size() > 0) {
                return (loginClass)resultados.get(0);
                
            } else {
                return null;
            }
        } finally {
            cerrar(rs);
            cerrar(ps);
            cerrar(conn);
        }
    }
    
     public void saveLogin(loginClass a, Connection conn)
            throws SQLException {
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement(SQL_INSERT);
            ps.setString(1, a.getUsuario());
            ps.setString(2, a.getPassword());
            ps.executeUpdate();
        } 
        finally {
            cerrar(ps);
            cerrar(conn);
        } 
     }
    
    private List getResults(ResultSet rs)
            throws SQLException {
        List results = new ArrayList();
        while (rs.next()) {
            loginClass a = new loginClass();
            a.setUsuario(rs.getString("usuario"));
            a.setPassword(rs.getString("password"));
            a.setTipoUsuario(rs.getString("CAT_TIPO_USUARIO_id_tipo"));
            results.add(a);
        }
        return results;
    }
    
    
    
    
    private void cerrar(Connection cnn) {
        if (cnn != null) {
            try {
                cnn.close();
            } catch (SQLException e) {
                //manejo del error
            }
        }
    }

    private void cerrar(PreparedStatement ps) {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                //manejo del error
            }
        }
    }

    private void cerrar(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                //manejo del error
            }
        }
    }   
}
